package com.bjc.nio.zerocopy;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @program: nettypro
 * @description:
 * @author: bjc
 * @create: 2021-09-05 21:07
 */
public class NewIOClient {

    public static void main(String[] args) throws Exception{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7002));
        String fileName = "D:\\iotest_delete\\seata-server-0.9.0.zip";

        //得到一个文件channel
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        long startTime = System.currentTimeMillis();
        //在linux下一个transferTo方法就可以完成传输
        //在windows下依次调用transferTo只能发送8m，就需要分段传输文件，而且要刷新传输时的位置
        //transferTo底层使用到零拷贝
        long channelSize = fileChannel.size();
        System.out.println(channelSize);
        long index = 0;
        long transferCount = 0L;
        int time = (int) (fileChannel.size()/(8*1024*1024));
        boolean remainder = (fileChannel.size()%(8*1024*1024))==0;
        if (!remainder){
            time = time+1;
        }
        System.out.println("time:"+time);
        for (int i = 1; i <= time; i++) {
            //8 * 1024 * 1024 8m
            boolean flag = (i * 8 * 1024 * 1024)>channelSize;
            long size = 0L;
            if (flag){
                size =  channelSize;
            }else {
                size = (i * 8 * 1024 * 1024);
            }
//            int size = ((i * 1024 * 1024) > fileChannel.size()) ? fileChannel.size() : size;
            transferCount += fileChannel.transferTo(index, size, socketChannel);
            index = size;
            System.out.println("此时：size="+size+",index="+index);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("发送总字节数："+transferCount+"，耗时："+(endTime-startTime));

        //关闭通道
        fileChannel.close();
    }
}
